<template>
  <audio ref="bgMusic" :autoplay="false" loop :src="musicSrc" hidden></audio>
</template>

<script setup>
import { ref, onMounted, computed, watch } from "vue";
import musicSrc from "@/assets/music/bg-music.mp3";
import { useMusicStore } from "@/store/index";
const store = useMusicStore();
const bgMusic = ref(null);
const volume = computed(() => store.volume);
const isPlay = computed(() => store.isPlay);

watch(
  volume,
  (newValue) => {
    if (bgMusic.value) {
      bgMusic.value.volume = newValue;
    }
  },
  {
    immediate: true,
  }
);

watch(
  isPlay,
  (newValue) => {
    if (bgMusic.value) {
      if (newValue) {
        bgMusic.value.play().catch((error) => {
          console.error("播放音乐失败:", error);
        });
      } else {
        bgMusic.value.pause();
      }
    }
  },
  {
    immediate: true,
  }
);

// onMounted(() => {
//   bgMusic.value.play().catch((error) => {
//     console.error("播放音乐失败:", error);
//   });
// });
</script>

<style scoped>
audio {
  opacity: 0;
}
</style>